package search

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"gopkg.in/yaml.v2"
)

var search_config, _ = loadConfig()

func loadConfig() (map[string]string, error) {
	config := map[string]string{}

	// 获取当前工作目录
	workDir, err := os.Getwd()
	if err != nil {
		log.Println("获取工作目录失败:", err)
		return nil, err
	}

	// 尝试多个可能的配置文件路径
	possiblePaths := []string{
		// 如果当前在项目根目录
		filepath.Join(workDir, "common", "search", "search_config.yaml"),
		// 如果当前在test目录
		filepath.Join(workDir, "..", "common", "search", "search_config.yaml"),
		// 如果当前在其他子目录
		filepath.Join(workDir, "..", "..", "common", "search", "search_config.yaml"),
	}

	for _, configPath := range possiblePaths {
		if data, err := ioutil.ReadFile(configPath); err == nil {
			if err := yaml.Unmarshal(data, config); err != nil {
				log.Println("读取配置文件失败", err)
				return nil, err
			}
			log.Println("成功读取配置文件:", configPath)
			return config, nil
		}
	}

	log.Println("配置文件不存在，尝试的路径:")
	for _, path := range possiblePaths {
		log.Println("  -", path)
	}
	return nil, nil
}

func Search(query string) (string, error) {
	apiKey := search_config["search_api_key"]
	endPoint := search_config["search_end_point"]
	headers := map[string]string{
		"Authorization": "Bearer " + apiKey,
		"Content-Type":  "application/json",
	}
	body := map[string]interface{}{
		"query":   query,
		"summary": true,
		"count":   20,
		"include": "blog.csdn.net",
	}

	// 将请求体转换为JSON
	jsonBody, err := json.Marshal(body)
	if err != nil {
		log.Printf("JSON序列化失败: %v", err)
		return "", err
	}

	// 创建HTTP请求
	req, err := http.NewRequest("POST", endPoint, strings.NewReader(string(jsonBody)))
	if err != nil {
		log.Printf("创建HTTP请求失败: %v", err)
		return "", err
	}

	// 设置请求头
	for key, value := range headers {
		req.Header.Set(key, value)
	}

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Printf("发送HTTP请求失败: %v", err)
		return "", err
	}
	defer resp.Body.Close()

	// 读取响应
	responseBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Printf("读取响应失败: %v", err)
		return "", err
	}

	// 检查HTTP状态码
	if resp.StatusCode != http.StatusOK {
		log.Printf("API请求失败，状态码: %d, 响应: %s", resp.StatusCode, string(responseBody))
		return "", fmt.Errorf("API请求失败，状态码: %d", resp.StatusCode)
	}

	return string(responseBody), nil
}
